package crawler.huatai;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zql.entity.AgencyEntity;

import dao.AgencyDao;
import util.HttpConnectionGet;
import util.MybatisTool;
import util.ProCity;
import util.TianYanCha;

public class HuaTaiQiCheCrawler {
	public List<AgencyEntity> getAgency() {
		List<AgencyEntity> list = new ArrayList<AgencyEntity>();
		//获取经销商
		String getDealer = "http://www.hawtaimotor.com/statics/images/dealers_js/dealers.js";
		String dealerText = HttpConnectionGet.getJson(getDealer);
		int startDealer = dealerText.indexOf("[{");
		int endDealer = dealerText.length()-2;
		dealerText = dealerText.substring(startDealer, endDealer);
		JSONArray dealers = JSON.parseArray(dealerText);
		for(int j=0;j<dealers.size();j++) {
			JSONObject dealer = dealers.getJSONObject(j);
			String name = dealer.getString("Title");
			String address = dealer.getString("Description");
			String sellTell = dealer.getString("Phone");
			String type = dealer.getString("Type");
			String[] lngAndLat = dealer.getString("Map").split("\\|");
			String lng = lngAndLat[0];
			String lat = lngAndLat[1];
			List<String> shareholder = TianYanCha.getShareholder(name);
			String sControllingShareholder = shareholder.get(0);
			String sOtherShareholders = shareholder.get(1);
			String[] proCity = ProCity.getData(lng,lat);
			String proName = proCity[0];
			String cityName = proCity[1];
			
			AgencyEntity agency = new AgencyEntity();
			agency.setdCloseDate(null);
			agency.setdOpeningDate(null);
			agency.setdUpdateTime(new Timestamp(System.currentTimeMillis()));
			agency.setnBrandID(-1);
			agency.setsBrand("华泰");

			agency.setnDealerIDWeb(-1);
			agency.setnManufacturerID(-1);
			agency.setsManufacturer("华泰汽车");

			agency.setnState(1);
			agency.setsAddress(address);
			agency.setsCity(cityName);
			agency.setsCustomerServiceCall(null);
			agency.setsDealerName(name);
			agency.setsDealerType(type);
			agency.setsProvince(proName);
			agency.setsSaleCall(sellTell);
			agency.setsLongitude(lng);
			agency.setsLatitude(lat);
			agency.setsControllingShareholder(sControllingShareholder);
			agency.setsOtherShareholders(sOtherShareholders);
			list.add(agency);
			
		}
		
		
		return list;
	}
	
	public static void main(String[] args) {
		HuaTaiQiCheCrawler crawler = new HuaTaiQiCheCrawler();
		System.out.println("爬虫开始...");
		List<AgencyEntity> agencys = crawler.getAgency();
		System.out.println("抓取完毕,正在存库");
		for(AgencyEntity agency : agencys) {
			MybatisTool.save(agency);
		}
		MybatisTool.close();
		System.out.println("请查看数据库");
		
	}

}
